import { messages } from "share/common";
import React from "react";

import { Form, Upload, Icon, message, Modal } from "antd";
const Dragger = Upload.Dragger;
import config from "config";
import FileViewer from "components/file-viewer";
import "styles/components/image-upload.scss";

import { connect } from "react-redux";
import pdfImage from "images/file-type/pdf.png";
import ofdImage from "images/file-type/ofd.png";
import { handleUploadOptions } from "share/utils";
import FileUpload from "components/upload/index";

/**
 * 图片上传组件
 *
 * 2018/11/26 zaranengap
 * 在系统组件中但是又不那么算是系统组件的东西
 * 很多字段定死了，默认值也是个业务接口
 * 系统组件不应该很纯粹吗，这么多业务字段是搞毛线啊
 * 但是很多定死的字段不是很正常吗
 * 很多库里的字段也是定死的啊
 * 这么一想我就不想动他了
 *
 */
class ImageUpload_noUse extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: "",
      fileList: [],
      result: [],
      previewIndex: 0, //预览图片的index
      imgIsUploading: false, //图片是否是正在上传的状态，用来解决 isShowDefault 为true时，上传过程中会出现显示两张图片的情况
    };
  }
  componentDidMount() {
    if (this.props.defaultFileList.length) {
      this.showDefaultFileList(this.props.defaultFileList);
    }
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.defaultFileList.length !== this.props.defaultFileList.length) {
      this.showDefaultFileList(nextProps.defaultFileList);
    }
    if (nextProps.isShowDefault) {
      if (nextProps.defaultFileList.splice && !this.state.imgIsUploading) {
        this.showDefaultFileList(nextProps.defaultFileList);
      }
    }
  }
  //为了显示默认已经上传的图片
  showDefaultFileList = (defaultFileList) => {
    const thumbUrl = (name) => {
      if (name.match(/.ofd$/)) return ofdImage;
      if (name.match(/.pdf$/)) return pdfImage;

      return void 0;
    };
    let fileList = [];
    defaultFileList.map((attachment) => {
      fileList.push({
        uid: attachment.attachmentOID || attachment.attachmentId || attachment.id,
        name: attachment.fileName,
        status: "done",
        thumbUrl: thumbUrl(attachment.fileName),
        url: attachment.fileURL,
      });
    });
    this.setState({ fileList, result: defaultFileList });
  };

  handleData = () => {
    return {
      attachmentType: this.props.attachmentType,
    };
  };

  getFileSize = () => {
    let { fileSize, loginCompany } = this.props;
    let maxFileSize = fileSize;
    if (loginCompany.enableLargeFile) {
      maxFileSize = 50;
    }
    return maxFileSize;
  };

  handleChange = (info) => {
    const { fileType, accept } = this.props;
    const fileSize = this.getFileSize();
    if (fileType) {
      //控制上传图片的类型
      let isFileType = false;
      fileType.map((type) => {
        let acceptList = accept.split(",");
        if (
          info.file.type === `image/${type}` ||
          acceptList.includes(info.file.type) ||
          (acceptList.includes(".ofd") && info.file.name.match(/.ofd$/))
        ) {
          isFileType = true;
        }
      });
      if (!isFileType && info.file.status !== "removed") {
        message.error(messages("common-1.key72") /*上传失败，文件格式错误*/);
        return;
      }
    }

    if (fileSize) {
      //控制上传图片的大小
      const isLtSize = info.file.size / 1024 / 1024 <= fileSize;
      if (!isLtSize && info.file.status !== "removed") {
        //上传失败，图片应不大于 {total} M
        message.error(
          messages("common-1.key73", {
            arg1: fileSize,
          }) /*上传失败，图片应不大于 {arg1} M*/
        );
        return;
      }
    }
    this.props.isUploading(true);
    this.setState({ imgIsUploading: true });
    let fileList = info.fileList;
    fileList.map((file) => {
      if (file.type === "application/pdf") {
        file.thumbUrl = pdfImage;
        file.url = info.file.response ? info.file.response.fileURL : file.thumbUrl;
      } else if (file.name.match(/.ofd$/)) {
        file.thumbUrl = ofdImage;
        file.url = info.file.response ? info.file.response.fileURL : file.thumbUrl;
      } else if (file.thumbUrl) {
        file.url = file.thumbUrl;
      }
    });
    this.setState({ fileList }, () => {
      const status = info.file.status;
      let { result } = this.state;
      if (status === "done") {
        message.success(`${info.file.name} ${messages("common-1.key60") /*上传成功*/}`);
        result.push(info.file.response);
        this.setState({ result, imgIsUploading: false }, () => {
          this.props.isUploading(false);
          this.props.onChange(result);
        });
      } else if (status === "error") {
        this.props.isUploading(false);
        this.setState({ imgIsUploading: false });
        let res = info.file.response;
        if (res && res.message) {
          message.error(res.message, 5);
        } else {
          message.error(`${info.file.name} ${messages("common-1.key59") /*上传失败*/}`);
        }
      } else if (status === "removed") {
        result.map((item, index) => {
          if (
            item.attachmentOID === (info.file.response ? info.file.response.attachmentOID : info.file.attachmentOID) ||
            item.attachmentOID === info.file.uid ||
            item.id === info.file.uid
          )
            result.splice(index, 1);
        });
        this.setState({ result, imgIsUploading: false }, () => {
          this.props.isUploading(false);
          this.props.onChange(result);
        });
      }
    });
  };

  //预览
  handlePreview = (file) => {
    this.state.fileList.map((item, index) => {
      if (item.uid === file.uid) {
        this.setState({
          previewIndex: index,
          previewVisible: true,
        });
      }
    });
  };

  clearImageList = () => {
    this.setState({ fileList: [] });
  };

  beforeUpload = (file, fileList) => {
    console.log("beforeUpload", file);
    let { beforeUpload } = this.props;
    const fileSize = this.getFileSize();
    let size = file.size;
    let result = true;
    if (beforeUpload) {
      result = beforeUpload();
    }
    if (size > fileSize * 1024 * 1024) {
      result = false;
    }
    return result;
  };

  render() {
    const { previewVisible, fileList, previewIndex } = this.state;
    const { className, accept } = this.props;
    const uploadButton = (
      <div>
        <Icon type="plus" style={{ fontSize: 32, color: "#999" }} />
        <div className="ant-upload-text" style={{ marginTop: 8, color: "#666" }}>
          {messages("common.upload") /*上传*/}
        </div>
      </div>
    );
    const upload_headers = {
      Authorization: "Bearer " + this.props.authToken.access_token,
    };
    let [uploadHeaders, uploadUrl] = handleUploadOptions(upload_headers, this.props.uploadUrl);
    let isDingTalkSSO = sessionStorage.getItem("isDingTalkSSO");
    let isWechatSSO = sessionStorage.getItem("isWechatSSO");
    let acceptProps = isDingTalkSSO === "true" || isWechatSSO === "true" ? {} : accept;
    return (
      <div className={`image-upload ${className || ""}`}>
        <div className="image-container">
          <Upload
            name="file"
            data={this.handleData}
            action={uploadUrl}
            headers={uploadHeaders}
            listType="picture-card"
            fileList={fileList}
            showUploadList={{ showRemoveIcon: !this.props.disabled }}
            beforeUpload={this.beforeUpload}
            onPreview={this.handlePreview}
            onChange={this.handleChange}
            accept={acceptProps}
          >
            {fileList.length >= this.props.maxNum || this.props.disabled ? null : uploadButton}
          </Upload>
        </div>
        {this.props.showMaxNum && !this.props.disabled && (
          <div>
            {
              messages("common.max.upload.image", {
                arg1: this.props.maxNum,
              }) /*最多上传 {arg1} 张图片*/
            }
          </div>
        )}
        {fileList.length > 0 && (
          <FileViewer
            visible={previewVisible}
            attachments={fileList}
            defaultIndex={previewIndex}
            onCancel={() => this.setState({ previewVisible: false, previewIndex: 0 })}
          />
        )}
      </div>
    );
  }
}

ImageUpload_noUse.propTypes = {
  uploadUrl: React.PropTypes.string, //上传URL
  attachmentType: React.PropTypes.string.isRequired, //附件类型
  defaultFileList: React.PropTypes.array, //默认上传的文件列表
  onChange: React.PropTypes.func, //上传成功后的回调
  maxNum: React.PropTypes.number, //最大上传文件的数量
  fileType: React.PropTypes.array, //上传文件的类型
  fileSize: React.PropTypes.number, //上传文件的大小
  isShowDefault: React.PropTypes.bool, //是否要进行回显，是否一直允许从父组件接受变化的图片列表
  disabled: React.PropTypes.bool, //是否禁用
  showMaxNum: React.PropTypes.bool, //是否显示最多上传多少图片
  isUploading: React.PropTypes.func, //图片是否在上传中
  accept: React.PropTypes.string, //附件只接受选择的类型
};

ImageUpload_noUse.defaultProps = {
  uploadUrl: `${config.baseUrl}/api/upload/attachment`,
  defaultFileList: [],
  onChange: () => {},
  maxNum: 9,
  isShowDefault: false,
  disabled: false,
  showMaxNum: false,
  isUploading: () => {},
  accept: "image/*",
  fileSize: 10,
};
function mapStateToProps(state) {
  return {
    authToken: state.main.authToken,
    loginCompany: state.login.loginCompany,
  };
}
// 注意
// defaultFileList里面的对象属性要有
//   attachmentOID,
//   fileName,
//   fileURL

// export default connect(mapStateToProps)(ImageUpload);
export default FileUpload;
